You are now starting to write Python programs that have a little substance. Your programs are growing a little longer, and there is a little more structure to your programs. This is a really good time to consider your overall style in writing code.
Python has gained a lot of respect as a programming language because of how readable the code is. You have seen that Python uses indentation to show which lines in a program are grouped together. This makes the structure of your code visible to anyone who reads it.
There are, however, some styling decisions we get to make as programmers that can make our programs more readable for ourselves, and for others.
There are several audiences to consider when you think about how readable your code is.
One of the earliest PEPs was a collection of guidelines for writing code that is easy to read. It was PEP 8, the Style Guide for Python Code.
When people want to suggest changes to the actual Python language, someone drafts a Python Enhancement Proposal.
There is a lot in there that won't make sense to you for some time yet, but there are some suggestions that you should be aware of from the beginning. Starting with good style habits now will help you write clean code from the beginning, which will help you make sense of your code as well.
Many editors have a setting that shows a vertical line that helps you keep your lines to a certain length.
That's all for now. We will go over more style guidelines as we introduce more complicated programming structures. If you follow these guidelines for now, you will be well on your way to writing readable code that professionals will respect.
PEP8 provides clear guidelines about where import statements should appear in a file. The names of modules should be on separate lines:
In [1]:
# this
import sys
import os
# not this
import sys, os
The names of classes can be on the same line:
In [3]:
from rocket import Rocket, Shuttle
Imports should always be placed at the top of the file. When you are working on a longer program, you might have an idea that requires an import statement. You might write the import statement in the code block you are working on to see if your idea works. If you end up keeping the import, make sure you move the import statement to the top of the file. This lets anyone who works with your program see what modules are required for the program to work.
Your import statements should be in a predictable order:
Modules should have short, lowercase names. If you want to have a space in the module name, use an underscore.
Class names should be written in CamelCase, with an initial capital letter and any new word capitalized. There should be no underscores in your class names.
This convention helps distinguish modules from classes, for example when you are writing import statements.
In [ ]:
# Ex 3.28 : Skim PEP 8
# put your code here
In [ ]:
# Ex 3.29 : Implement PEP 8
# put your code here